package com.dingreading.cloud.soms.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.dto.StaffLoginDto;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.soms.entity.Staff;
import com.dingreading.cloud.soms.entity.Stores;
import com.dingreading.cloud.soms.service.AppProjectService;
import com.dingreading.cloud.soms.service.StaffRolesService;
import com.dingreading.cloud.soms.service.StaffService;
import com.dingreading.cloud.soms.service.StoresService;
import com.dingreading.cloud.soms.util.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front/auth")
@Api(tags = "门店-授权验证管理")
public class FrontAuthController {

    @Resource
    protected AppProjectService appProjectService;
    @Resource
    protected StoresService storesService;
    @Resource
    protected StaffService staffService;
    @Resource
    protected StaffRolesService staffRolesService;
    @Resource
    protected RedisService redisService;

//    String callback = "http://scs.dingreading.com:8080/storeSubject";
//    String callback = "https://test.dingreading.com/storeSubject";
//    String callback = "https://www.dingreading.com/storeSubject";

    @ApiOperation(value = "验证用户信息")
    @PostMapping(value = "/userToken")
    public R<Object> userToken(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid", required = false) String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid", required = false) String storeUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "currentstoreuid", required = false) String currentstoreuid
    ) {
//        System.out.println("接口验证开始...");

        // 网页地址
        String htmlUrl = HttpRequestUtil.getHtmlUrl(request);
        if (StringUtils.isBlank(htmlUrl))
            return R.fail("网页地址获取失败");

        // 根据网页地址获取模块id
        String appId = LoginAuthUtil.getAppId(htmlUrl);
        if (StringUtils.isBlank(appId))
            return R.fail("应用Id获取失败");

        // 获取应用的秘钥
        String appSecret = getAppSecret(appId);
        if (StringUtils.isBlank(appSecret))
            return R.fail("应用秘钥获取失败");

        // 获取cookieValue
        Cookie cookie = CookiesUtil.getCookieByName(request, LoginAuthUtil.DDPB_TOKEN);
        if (cookie == null || StringUtils.isBlank(cookie.getValue())) {
            // 获取cookieValue失败，去登录
            String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(-1, "token校验失败", loginUrl);
        }

        // 根据cookieValue获取redis里的登录信息
        String cookieValue = cookie.getValue();
        String loginJson = (String) redisService.get(RedisParam.STAFF_LOGIN + cookieValue);

        LoginDataDto loginDataDto = null;
        if (StringUtils.isBlank(loginJson)) {
            // 发起请求获取登录信息
            String ip = IpUtil.getIpAddr(request);
            R<Object> r = LoginAuthUtil.getLoginInfo(appId, appSecret, htmlUrl, cookieValue, ip);
            if (R.isError(r))
                return r;

            loginDataDto = (LoginDataDto) r.getData();
            // redis保存10分钟
            redisService.set(RedisParam.STAFF_LOGIN + cookieValue, JsonUtil.toJsonString(loginDataDto), RedisParam.MINUTE_TIME);
        } else {
            // 获取redis里的登录信息
            loginDataDto = JSONObject.parseObject(loginJson, LoginDataDto.class);
        }

        // 轻创加盟没有权限
        if (loginDataDto.getCurrentOperationType().equals(EnumOperationType.EASY_PRODUCT_JOIN.getType())) {
            String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(-1, "轻创加盟没有该模块权限", loginUrl);
        }

        // 门店uid切换后，更新缓存的门店uid
        if (StringUtils.isNotBlank(currentstoreuid) && !loginDataDto.getCurrentStoreUid().equals(currentstoreuid)) {
            Stores stores = storesService.getByCorpUidAndStoreUid(null, currentstoreuid);
            if (null == stores) {
                String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
                return R.fail(-1, "门店信息未查询到", loginUrl);
            }

            boolean existStoreUid = staffRolesService.existStoreUid(currentstoreuid, loginDataDto.getStaffUid());
            if (!existStoreUid) {
                String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
                return R.fail(-1, "账号没有该门店的权限", loginUrl);
            }

            loginDataDto.setCorpUid(stores.getCorpUid());
            loginDataDto.setCurrentStoreId(stores.getId());
            loginDataDto.setCurrentStoreUid(currentstoreuid);
            loginDataDto.setCurrentStoreName(stores.getStoreName());
            if (StringUtils.isNotBlank(stores.getCooperationType())) {
                List<Integer> cpts = Arrays.stream(StringUtils.split(stores.getCooperationType(), ","))
                        .map(Integer::parseInt).collect(Collectors.toList());
                loginDataDto.setCurrentCooperationTypes(cpts);
            }
            loginDataDto.setCurrentOperationType(stores.getOperationType());
            redisService.set(RedisParam.STAFF_LOGIN + cookieValue, JsonUtil.toJsonString(loginDataDto), RedisParam.MINUTE_TIME);
        }

        Staff staff = staffService.getByUid(loginDataDto.getStaffUid());
        // 0.普通员工 1.店长 2.市场
        int staffRole = AccountUtil.isStaffRole(loginDataDto.getStoreRoles());
        StaffLoginDto staffDto = new StaffLoginDto();
        staffDto.setCorpUid(loginDataDto.getCorpUid());
        staffDto.setStoreUid(loginDataDto.getCurrentStoreUid());
        staffDto.setStaffUid(loginDataDto.getStaffUid());
        staffDto.setStoreName(loginDataDto.getCurrentStoreName());
        staffDto.setFullName(loginDataDto.getFullName());
        staffDto.setNickName(loginDataDto.getNickName());
        staffDto.setUsername(loginDataDto.getUsername());
        staffDto.setStoreMgr(staffRole);
        staffDto.setCurrentCooperationTypes(loginDataDto.getCurrentCooperationTypes());
        staffDto.setCurrentOperationType(loginDataDto.getCurrentOperationType());
        if (staff != null) {
            staffDto.setPubPhone(staff.getPubPhone());
            staffDto.setPriPhone(staff.getPriPhone());
        }

        return R.ok(staffDto);
    }

    /**
     * 获取应用秘钥
     */
    private String getAppSecret(String appId) {
        String appSecret = (String) redisService.get(RedisParam.APP_PROJECT + appId);
        if (StringUtils.isBlank(appSecret)) {
            appSecret = appProjectService.getAppSecret(appId);

            if (StringUtils.isNotBlank(appSecret))
                redisService.set(RedisParam.APP_PROJECT + appId, appSecret, RedisParam.HOUR_TIME);
        }

        return appSecret;
    }

}